package com.nbjtjc.safe.service.report;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.util.PoiMergeCellUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.nbjtjc.safe.bean.Page;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.emg.*;
import com.nbjtjc.safe.mapper.emg.handle.EmgHandleReportMapper;
import com.nbjtjc.safe.mapper.sys.SysDeptMapper;
import com.nbjtjc.safe.mapper.sys.SysUserMapper;
import com.nbjtjc.safe.model.EmgPlanPublicGoodsHistory;
import com.nbjtjc.safe.model.emg.EmgPlanPublic;
import com.nbjtjc.safe.model.emg.EmgPlanPublicSummary;
import com.nbjtjc.safe.model.emg.EmgWorkBrief;
import com.nbjtjc.safe.model.emg.handle.EmgHandleReport;
import com.nbjtjc.safe.model.sys.SysDept;
import com.nbjtjc.safe.model.sys.SysUser;
import com.nbjtjc.safe.util.FileUtil;
import com.nbjtjc.safe.util.MyShiroUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @auther guqianbin
 * @date 2018/4/20 16:21
 **/
@Service
public class EmgReportService {

    @Autowired
    private EmgPlanPublicMapper emgPlanPublicMapper;

    @Autowired
    private EmgPlanPublicSummaryMapper emgPlanPublicSummaryMapper;

    @Autowired
    private EmgWorkBriefMapper emgWorkBriefMapper;

    @Autowired
    private EmgGoodsMapper emgGoodsMapper;
    @Autowired
    private EmgPlanPublicGoodsMapper emgPlanPublicGoodsMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private EmgHandleReportMapper emgHandleReportMapper;

    @Autowired
    private EmgPlanPublicGoodsHistoryMapper emgPlanPublicGoodsHistoryMapper;
    //TODO 临时文件的清理
    @Value("${file.path.tempPath}")
    private String fileTempPath;

    @Autowired
    private FileUtil fileUtil;


    public Result emgReportFileList(int emgPlanPublicId) {
        Result result = new Result();
        EmgPlanPublic emgPlanPublic = emgPlanPublicMapper.selectByPrimaryKey(emgPlanPublicId);
        if (ObjectUtil.isNotNull(emgPlanPublic)) {
            EmgPlanPublic temp = new EmgPlanPublic();
            temp.setStartPlanId(emgPlanPublic.getStartPlanId());
            List<EmgPlanPublic> emgPlanPublics = emgPlanPublicMapper.search(temp, new Page());
            result.setData(emgPlanPublics);
        } else {
            result.setFalse();
        }
        return result;

    }


    /**
     * 获取某个应急预案的报表
     *
     * @return
     */
    public void emgPlanPublicsExcel(HttpServletResponse response, int emgPlanPublicId) throws IOException {
        EmgPlanPublic emgPlanPublic = new EmgPlanPublic();
        emgPlanPublic.setId(emgPlanPublicId);
        List<EmgPlanPublic> emgPlanPublics = emgPlanPublicMapper.search(emgPlanPublic, null);
        if (CollectionUtil.isEmpty(emgPlanPublics)) {
            return;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        if (CollectionUtil.isNotEmpty(emgPlanPublics.get(0).getEmgDuties())) {
            map.put("duties", emgPlanPublics.get(0).getEmgDuties());
        }
        map.put("planPublic", emgPlanPublics.get(0));
        TemplateExportParams params = new TemplateExportParams(
                "reportTemplates/emgPlanPublic.xlsx");
//        params.setHeadingStartRow(0);
//        params.setHeadingRows(5);
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);

        PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 0, 0, 12);
        File savefile = new File(fileTempPath);
        if (!savefile.exists()) {
            savefile.mkdirs();
        }
        String filePath = fileTempPath + "emgPlanPublic-" + emgPlanPublicId + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
        FileOutputStream fos = new FileOutputStream(filePath);
        workbook.write(fos);
        fos.close();
        fileUtil.writeFile(response, new File(filePath));
    }

    /**
     * 返回应急工作总结的excel模板
     *
     * @param response
     * @param emgPlanPublicId
     * @return
     */
    public Result emgSummaryExcel(HttpServletResponse response, int emgPlanPublicId,int companyId) {
        Result result = new Result();
        try {
            EmgPlanPublicSummary emgPlanPublicSummary = new EmgPlanPublicSummary();
            emgPlanPublicSummary.setPlanPublicId(emgPlanPublicId);
            emgPlanPublicSummary.setCompanyId(companyId);
            List<EmgPlanPublicSummary> emgPlanPublicSummaries =
                    emgPlanPublicSummaryMapper.search(emgPlanPublicSummary, null);
            if (CollectionUtil.isEmpty(emgPlanPublicSummaries)) {
                result.setFalse("该总结报告没有总结报告");
                return result;
            }
            EmgPlanPublic emgPlanPublic = emgPlanPublicMapper.selectByPrimaryKey(emgPlanPublicId);

            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/emgSummary.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(5);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("summary", emgPlanPublicSummaries.get(0));
            map.put("emgPlanName", emgPlanPublic.getName());
            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 5, 0, 7);
            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            String filePath = fileTempPath + "emgSummary-" + emgPlanPublicId + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            fileUtil.writeFile(response, new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
            result.setFalse();
        }
        return result;
    }

    /**
     * 返回某个应急响应的工作简报的excel文件
     *
     * @param emgPlanPublicId
     * @return
     */
    public Result emgWorkBriefExcel(HttpServletResponse response, int emgPlanPublicId,int companyId) {
        Result result = new Result();
        try {
            EmgWorkBrief emgWorkBrief = new EmgWorkBrief();
            emgWorkBrief.setCompanyId(companyId);
            emgWorkBrief.setPlanPublicId(emgPlanPublicMapper.getStartPlanPublicId(emgPlanPublicId));
            List<EmgWorkBrief> emgWorkBriefs = emgWorkBriefMapper.search(emgWorkBrief, new Page());
            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/workBrief.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(5);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("briefs", emgWorkBriefs);

            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 5, 0, 7);
            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            String filePath = fileTempPath + "workBrief-" + emgPlanPublicId + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            fileUtil.writeFile(response, new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
            result.setFalse();
        }
        return result;
    }

    /**
     * 应急工作的物资报表的导出
     *
     * @param response
     * @param emgPlanPublicId
     * @return
     */
    public Result emgPlanGoodsExcel(HttpServletResponse response, int emgPlanPublicId) {
        Result result = new Result();
        try {
            EmgPlanPublicGoodsHistory emgPlanPublicGoodsHistory = new EmgPlanPublicGoodsHistory();
            emgPlanPublicGoodsHistory.setEmgPlanPublicId(emgPlanPublicId);
            List<EmgPlanPublicGoodsHistory> emgPlanPublicGoodsHistories =
                    emgPlanPublicGoodsHistoryMapper.select(emgPlanPublicGoodsHistory);
            EmgPlanPublic emgPlanPublic = emgPlanPublicMapper.selectByPrimaryKey(emgPlanPublicId);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("goods", emgPlanPublicGoodsHistories);
            map.put("deptName", sysDeptMapper.findNameById(MyShiroUtils.getDeptId()));
            map.put("deptName", " 信息技术研究所");
            map.put("docNum", " ");
            map.put("recordNum", " ");
            map.put("emgPlanName", emgPlanPublic.getName());
            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/emgGoods.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(2);

            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 2, 0, 7);
            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            String filePath = fileTempPath + "emgGoods-" + emgPlanPublicId + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
//            String filePath = fileTempPath + "emgGoods-" + emgPlanPublicId + "-" + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            fileUtil.writeFile(response, new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
            result.setFalse();
        }
        return result;
    }


    /**
     * 应急事件的重大事件报告单
     *
     * @param response
     * @param eventId
     * @return
     */
    public void emgReportExcel(HttpServletResponse response, int eventId) {
        if (eventId <= 0) {
            return;
        }

        List<EmgHandleReport> emgHandleReports = emgHandleReportMapper.findByEventId(eventId);
        if (CollectionUtil.isEmpty(emgHandleReports)) {
            return;
        }
        //取id最大的
        try {
            EmgHandleReport emgHandleReport = emgHandleReports.get(0);
            SysUser reportUser = sysUserMapper.selectByUserId(emgHandleReport.getReportUserId());
            SysDept reportDept = sysDeptMapper.selectByPrimaryKey(emgHandleReport.getReportUnitDeptId());
            SysUser deptLeaderUser = sysUserMapper.selectByUserId(reportDept.getLeaderUserId());
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("report", emgHandleReport);
            map.put("reportDeptName", reportDept.getName());
            map.put("reportUser", reportUser);
            map.put("managerUsername", ObjectUtil.isNull(deptLeaderUser) ? "" : deptLeaderUser.getUsername());

            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/emgReport.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(2);

            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 2, 0, 4);
            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            String filePath = fileTempPath + "emgHandleReport-" + eventId + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            fileUtil.writeFile(response, new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
